﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Profile;
using ClientApp.Models;
using CommonApp;
using CommonApp.Models;
using IBS.Bll;
using IBS.Bll.Accounts;
using IBS.Bll.Authority;
using IBS.Bll.AutoPayments;
using IBS.Bll.Cards;
using IBS.Bll.KnowledgeBase;
using IBS.Bll.Payments;
using IBS.Bll.Security;
using IBS.Bll.Transfers;
using IBS.Dal;
using IBS.Model;
using IBS.ServiceContracts;

namespace ClientApp.Controllers
{
    [Authorize(Roles = "user")]
    public class AutoPaymentsController : Controller
    {
        private IAuthorityService authorityService;
        private IKnowledgeBaseService knowledgeBaseService;
        private ICardService cardService;
        private IPaymentService paymentService;
        private IAccountService accountService;
        private ITransferService transferService;
        private IAutoPaymentService autoPaymentService;

        private readonly OperationStep[] steps = new[]
                                                     {

                                                         new OperationStep
                                                             {
                                                                 Uid = "cardsMenuItem",
                                                                 Name = "Cards",
                                                                 GoTo = "/AutoPayments"
                                                             },
                                                         new OperationStep
                                                             {
                                                                 Uid = "paymentMenuItem",
                                                                 Name = "Payment selection",
                                                                 IsVisible = false,
                                                                 GoTo = "/AutoPayments/SelectPayment"

                                                             },
                                                         new OperationStep
                                                             {
                                                                 Uid = "paymentDetailMenuItem",
                                                                 Name = "Maintenance",
                                                                 IsVisible = false,
                                                                 GoTo = "/AutoPayments/Maintenance"
                                                             },
                                                         new OperationStep
                                                             {
                                                                 Uid = "autoPaymentStatementMenuItem",
                                                                 Name = "Statement",
                                                                 IsVisible = false,
                                                                 GoTo = "/AutoPayments/Statement"
                                                             },

                                                         new OperationStep
                                                             {Uid = "homeMenuItem", Name = "Back", GoTo = "/Home/Index"}
                                                     };

        public AutoPaymentsController()
        {
            var container = new IbsContainer();
            this.authorityService = container.AuthorityService;
            this.accountService = container.AccountService;
            this.transferService = container.TransferService;
            this.cardService = container.CardService;
            this.paymentService = container.PaymentService;
            this.autoPaymentService = container.AutoPaymentService;
        }

        public ActionResult Index()
        {
            ViewBag.Steps = steps;
            ViewBag.ActiveStep = steps[0];

            var client = authorityService.GetClientByUserName(User.Identity.Name);

            IEnumerable<Card> cards = null;

            try
            {
                cards = cardService.GetClientsCard(client, c => !c.IsBlocked);
            }
            catch (BusinessException be)
            {
                ModelState.AddModelError("", be.Message);
            }

          
            ViewBag.AutoPayment = new AutoPaymentModel();
            ViewBag.AccountService = accountService;
            ViewBag.Steps = steps;
            ViewBag.ActiveStep = steps[0];
            return View(cards);
        }

        [HttpPost]
        public ActionResult SelectPayment(AutoPaymentModel autoPayment)
        {
            ViewBag.AutoPayment = autoPayment;
            ViewBag.Steps = steps;
            steps[1].IsVisible = true;
            ViewBag.ActiveStep = steps[1];
            ViewBag.AutoPayment = autoPayment;
            ViewBag.CardNumber = autoPayment.CardNumber;
            ViewBag.FormGoTo = Url.Action("Maintenance");
            // ViewBag.EnsureSecurity = true;

            return View();
        }

        [HttpPost]
        public ActionResult Maintenance(AutoPaymentModel autoPayment)
        {
            if (autoPayment.PaymentId != null)
            {
                var payment = paymentService.GetPaymentById(autoPayment.PaymentId.Value);
            }
            //Uncommit if you want to fill in database
            // autoPaymentService.CreateAutoPayment(paymentId, payment.PaymentDetailTemplate, cardNumber, 10, 10m, "USD");
            ViewBag.Steps = steps;
            ViewBag.AutoPayment = autoPayment;
            steps[2].IsVisible = true;
            steps[1].IsVisible = true;
            ViewBag.ActiveStep = steps[2];
            ViewBag.CardNumber = autoPayment.CardNumber;
            ViewBag.PaymentId = autoPayment.PaymentId;
            ViewBag.EnsureSecurity = true;
            var card = cardService.GetCardByNumber(autoPayment.CardNumber);
      
            return View();
        }

        public ActionResult MaintenanceJSON(AutoPaymentModel autoPayment, int? start)
        {
            if (autoPayment.PaymentId != null)
            {
                var payment = paymentService.GetPaymentById(autoPayment.PaymentId.Value);
                //Uncommit if you want to fill in database
                //autoPaymentService.CreateAutoPayment(payment.Id, payment.PaymentDetailTemplate, autoPayment.CardNumber,
                //                                     10, 10m, "USD");
            }

            var card = cardService.GetCardByNumber(autoPayment.CardNumber);
            int? page = 1;
            if (autoPayment.Start.HasValue)
            {
                page = autoPayment.Start.Value / Configuration.RecordPerPage + 1;
            }
            int totalCount;
            IList<AutoPayment> model = PagingHelper.Paging<AutoPayment>(autoPaymentService.GetAutoPayments,
                a => a.FromCardId == card.Id && a.ToPaymentId == autoPayment.PaymentId,
                page.Value,
                out totalCount);

             var result = model                    
                    .Select(
                        (x, i) => new { Id = x.Id, Number = i, Amount = x.Amount, DayOfMonth = x.DayOfMonth, ISO = x.ISO })
                    .ToList();
            var response = new { totalCount = totalCount, topics = result };
            return Json(response);
        }

        [HttpPost]
        public ActionResult Statement(AutoPaymentStatementModel statementModel)
        {
            ViewBag.Steps = steps;
            steps[1].IsVisible = true;
            steps[2].IsVisible = true;
            steps[3].IsVisible = true;
            ViewBag.ActiveStep = steps[3];
            ViewBag.AutoPayment = statementModel;
            if (statementModel.FromDate != null)
                ViewBag.FromDate = statementModel.FromDate.Value.ToString("MM/dd/yyyy");

            if (statementModel.ToDate != null)
                ViewBag.ToDate = statementModel.ToDate.Value.ToString("MM/dd/yyyy");
            if (!statementModel.Page.HasValue)
                statementModel.Page = 1;

            int totalCount;
            IList<Transfer> model = PagingHelper.Paging<Transfer>(transferService.GetTransfers,
                a =>
                    (TransferType)a.TransferType ==
                    TransferType.ToAutoPayment &&
                    a.ToAutoPaymentId == statementModel.AutoPaymentId &&

                    (!statementModel.FromDate.HasValue ||
                      statementModel.FromDate.HasValue && a.StartDate.Date >= statementModel.FromDate.Value.Date) &&

                     (!statementModel.ToDate.HasValue ||
                      statementModel.ToDate.HasValue && a.StartDate.Date <= statementModel.ToDate.Value.Date)

                , statementModel.Page.Value, out totalCount);

            ViewBag.CurrentPage = statementModel.Page;
            ViewBag.TotalRecordsCount = totalCount;

            return View(model);
        }
        
        public ActionResult Load(AutoPaymentModel autoPayment)
        {
            if (autoPayment.AutoPaymentId != null)
            {
                var autoPaymentResult = autoPaymentService.GetAutoPaymentById(autoPayment.AutoPaymentId.Value);

                var result = ("{" + String.Format(" \"amount\": \"{0}\", \"currency\": \"{1}\", \"dayOfMonth\": {2} ,\"detail\": {3}",
                    autoPaymentResult.Amount, autoPaymentResult.ISO, autoPaymentResult.DayOfMonth, autoPaymentResult.PaymentDetail)
                    + "}").Replace("\\", "\\\\");
                return Content(result, "application/json");
            }
            return Content("");
        }
        
        public ActionResult Create(AutoPaymentModel autoPayment)
        {
            if (autoPayment.PaymentId != null)
            {

                var payment = paymentService.GetPaymentById(autoPayment.PaymentId.Value);

                autoPaymentService.CreateAutoPayment(payment.Id, autoPayment.PaymentDetail, autoPayment.CardNumber,
                                                     autoPayment.DayOfMonth, autoPayment.Amount, autoPayment.Currency);
            }
           return Content("{success:true, errorCode:-1,error:\"\"}", "json");
        }

        public ActionResult Update(AutoPaymentModel autoPayment)
        {
            if (autoPayment.AutoPaymentId != null)
            {
                var autoPaymentResult = autoPaymentService.GetAutoPaymentById(autoPayment.AutoPaymentId.Value);
                autoPaymentResult.Amount = autoPayment.Amount;
                autoPaymentResult.ISO = autoPayment.Currency;
                autoPaymentResult.DayOfMonth = autoPayment.DayOfMonth;
                autoPaymentResult.PaymentDetail = autoPayment.PaymentDetail;

                autoPaymentService.UpdateAutoPayment(autoPaymentResult);
            }
            return Content("{success:true, errorCode:-1,error:\"\"}", "json");
        }

        public ActionResult Delete(AutoPaymentModel autoPayment)
        {
            if (autoPayment.AutoPaymentId != null)
            {
                autoPaymentService.DeleteAutoPayment(autoPayment.AutoPaymentId.Value);
            }
            return Json(new { CheckResult = "success" });
        }
    }
}
